<template>
  <div>
    <a-upload
      name="file"
      listType="picture-card"
      :multiple="multipleFlag"
      :action="uploadAction"
      :headers="headers"
      :data="{imgtype:bizPath}"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      :disabled="disabled"
      @change="handleChange"
      @preview="handlePreview">
      <div v-show="!disabled" v-if="fileList.length<fileMaxSize">
        <div>
          <a-icon :type="uploadLoading ? 'loading' : 'plus'"/>
          <div class="ant-upload-text">{{ text }}</div>
        </div>
      </div>
    </a-upload>
    <a-modal
      :visible="previewVisible"
      :footer="null"
      @cancel="handleCancel()">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>

<script>
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    const reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
  return path.substring(path.lastIndexOf('/') + 1)
}
export default {
  name: 'WImageUpload',
  data () {
    return {
      uploadAction: process.env.VUE_APP_API_BASE_URL + 'publicinterface/getImgurlbyfile',
      uploadLoading: false,
      picUrl: false,
      headers: {},
      fileList: [],
      previewImage: '',
      previewVisible: false
    }
  },
  props: {
    text: {
      type: String,
      required: false,
      default: '上传'
    },
    /* 这个属性用于控制文件上传的业务路径 */
    bizPath: {
      type: String,
      required: false,
      default: 'temp'
    },
    value: {
      type: [String, Array],
      required: false,
      default: ''
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    multipleFlag: {
      type: Boolean,
      required: false,
      default: false
    },
    fileMaxSize: {
      type: Number,
      required: false,
      default: 10
    }
  },
  watch: {
    value (val) {
      if (val instanceof Array) {
        this.initFileList(val.join(','))
      } else {
        this.initFileList(val)
      }
    }
  },
  created () {
    const token = storage.get(ACCESS_TOKEN)
    this.headers = { 'X-Access-Token': token }
    if (this.value instanceof Array) {
      this.initFileList(this.value.join(','))
    } else {
      this.initFileList(this.value)
    }
  },
  methods: {
    initFileList (paths) {
      if (!paths || paths.length === 0) {
        this.fileList = []
        return
      }
      this.picUrl = true
      const fileList = []
      const arr = paths.split(',')
      for (var a = 0; a < arr.length; a++) {
        const url = this.$getFileAccessHttpUrl(arr[a])
        fileList.push({
          uid: uidGenerator(),
          name: getFileName(arr[a]),
          status: 'done',
          url: url,
          response: {
            status: 'history',
            content: arr[a]
          }
        })
      }
      this.fileList = fileList
    },
    beforeUpload: function (file) {
      return new Promise((resolve, reject) => {
        var fileType = file.type
        if (fileType.indexOf('image') < 0) {
          this.$message.warning('请上传图片')
          return reject(false)
        }
        const isLt2M = file.size / 1024 / 1024 < 20
        if (!isLt2M) {
          this.$message.error('上传的图片必须小于20MB!')
          return reject(false)
        }
        return resolve(true)
      })
    },
    handleChange (info) {
      this.picUrl = false
      let fileList = info.fileList
      if (info.file.status === 'done') {
        if (info.file.response.code === '0000') {
          this.picUrl = true
          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.content
            }
            return file
          })
        } else {
          this.$message.error(info.file.response.content)
        }
        // this.$message.success(`${info.file.name} 上传成功!`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      } else if (info.file.status === 'removed') {
        this.handleDelete(info.file)
      }
      this.fileList = fileList
      if (info.file.status === 'done' || info.file.status === 'removed') {
        this.handlePathChange()
      }
    },
    // 预览
    handlePreview (file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    getAvatarView () {
      if (this.fileList.length > 0) {
        const url = this.fileList[0].url
        return this.$getFileAccessHttpUrl(url)
      }
    },
    handlePathChange () {
      const uploadFiles = this.fileList
      let path = ''
      if (!uploadFiles || uploadFiles.length === 0) {
        path = ''
      }
      const arr = []
      if (!this.multipleFlag) {
        if (uploadFiles.length > 0) {
          arr.push(uploadFiles[uploadFiles.length - 1].response.content)
        }
      } else {
        for (var a = 0; a < uploadFiles.length; a++) {
          arr.push(uploadFiles[a].response.content)
        }
      }
      if (arr.length > 0) {
        path = arr.join(',')
      }
      this.$emit('change', path)
    },
    handleDelete (file) {
      // 如有需要新增 删除逻辑
      console.log(file)
    },
    handleCancel () {
      this.close()
      this.previewVisible = false
    },
    close () {

    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style>
.ant-upload.ant-upload-disabled {
  display: none !important;
}
</style>
